package com.mccree.elasticsearch.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: MccRee
 * @Date: 2022/5/20 11:06
 */
@Configuration
public class ElasticSearchConfig{
    @Value("${es.port}")
    private int port;

    @Value("${es.hostname}")
    private String host;

    @Bean(name = "esClient")
    public ElasticsearchClient createEsClient(){
        RestClient httpClient = RestClient.builder(
                new HttpHost(host, port)
        ).build();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        RestClientTransport transport = new RestClientTransport(httpClient, new JacksonJsonpMapper(objectMapper));
        return new ElasticsearchClient(transport);
    }
}
